<template>
  <el-dialog
    v-model="dialogVisible"
    :title="tableInfo.name || '表详情'"
    width="80%"
    :before-close="handleClose"
  >
    <div class="table-detail">
      <!-- 基本信息 -->
      <el-card class="mb-16">
        <template #header>
          <span>基本信息</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="表名">{{ tableInfo.name }}</el-descriptions-item>
          <el-descriptions-item label="表类型">
            <el-tag :type="getTableTypeTagType(tableInfo.type)">
              {{ getTableTypeLabel(tableInfo.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述">{{ tableInfo.comment || '暂无描述' }}</el-descriptions-item>
          <el-descriptions-item label="存储引擎">Doris</el-descriptions-item>
          <el-descriptions-item label="行数">{{ formatNumber(tableInfo.rowCount) }}</el-descriptions-item>
          <el-descriptions-item label="数据大小">{{ tableInfo.dataSize }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(tableInfo.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatTime(tableInfo.lastUpdated) }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 字段信息 -->
      <el-card class="mb-16">
        <template #header>
          <span>字段信息</span>
        </template>
        <el-table :data="columns" stripe max-height="300">
          <el-table-column label="字段名" prop="name" width="150" />
          <el-table-column label="类型" prop="type" width="120" />
          <el-table-column label="长度" prop="length" width="80" />
          <el-table-column label="是否为空" prop="nullable" width="100">
            <template #default="{ row }">
              <el-tag :type="row.nullable ? 'warning' : 'success'" size="small">
                {{ row.nullable ? '可为空' : '不为空' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="默认值" prop="defaultValue" width="120" />
          <el-table-column label="描述" prop="comment" min-width="200" />
        </el-table>
      </el-card>

      <!-- 血缘关系 -->
      <el-card class="mb-16">
        <template #header>
          <span>血缘关系</span>
        </template>
        <el-row :gutter="16">
          <el-col :span="12">
            <h4>上游依赖</h4>
            <div v-if="upstreamTables.length === 0" class="empty-lineage">
              暂无上游依赖
            </div>
            <div v-else class="lineage-list">
              <div
                v-for="table in upstreamTables"
                :key="table.id"
                class="lineage-item"
                @click="viewTable(table.id)"
              >
                <div class="table-type-indicator" :class="table.type"></div>
                <div class="table-info">
                  <div class="table-name">{{ table.name }}</div>
                  <div class="table-desc">{{ table.comment }}</div>
                </div>
                <el-tag size="small" :type="getRelationTagType(table.relation)">
                  {{ getRelationLabel(table.relation) }}
                </el-tag>
              </div>
            </div>
          </el-col>
          
          <el-col :span="12">
            <h4>下游依赖</h4>
            <div v-if="downstreamTables.length === 0" class="empty-lineage">
              暂无下游依赖
            </div>
            <div v-else class="lineage-list">
              <div
                v-for="table in downstreamTables"
                :key="table.id"
                class="lineage-item"
                @click="viewTable(table.id)"
              >
                <div class="table-type-indicator" :class="table.type"></div>
                <div class="table-info">
                  <div class="table-name">{{ table.name }}</div>
                  <div class="table-desc">{{ table.comment }}</div>
                </div>
                <el-tag size="small" :type="getRelationTagType(table.relation)">
                  {{ getRelationLabel(table.relation) }}
                </el-tag>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 统计信息 -->
      <el-card>
        <template #header>
          <span>统计信息</span>
        </template>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-statistic title="总行数" :value="tableInfo.rowCount || 0" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="字段数" :value="columns.length" />
          </el-col>
          <el-col :span="8">
            <el-statistic title="索引数" :value="3" />
          </el-col>
        </el-row>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="viewLineage">查看血缘图</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { formatTime } from '@/utils/date'

const props = defineProps({
  modelValue: Boolean,
  tableId: [String, Number]
})

const emit = defineEmits(['update:modelValue'])

const router = useRouter()

// 响应式数据
const tableInfo = ref({})
const columns = ref([])
const upstreamTables = ref([])
const downstreamTables = ref([])

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听tableId变化
watch(() => props.tableId, (newVal) => {
  if (newVal) {
    fetchTableDetail(newVal)
  }
})

// 获取表详情
const fetchTableDetail = async (tableId) => {
  // 模拟API调用
  await new Promise(resolve => setTimeout(resolve, 500))
  
  // 模拟数据
  if (tableId === 'fact_orders') {
    tableInfo.value = {
      id: 'fact_orders',
      name: 'fact_orders',
      comment: '订单事实表，存储所有订单相关信息',
      type: 'fact',
      rowCount: 1540000,
      dataSize: '2.3GB',
      createTime: new Date('2023-01-15'),
      lastUpdated: new Date(Date.now() - 3600000)
    }
    
    columns.value = [
      {
        name: 'order_id',
        type: 'BIGINT',
        length: 20,
        nullable: false,
        defaultValue: null,
        comment: '订单ID'
      },
      {
        name: 'customer_id',
        type: 'BIGINT',
        length: 20,
        nullable: false,
        defaultValue: null,
        comment: '客户ID'
      },
      {
        name: 'product_id',
        type: 'BIGINT',
        length: 20,
        nullable: false,
        defaultValue: null,
        comment: '产品ID'
      },
      {
        name: 'order_date',
        type: 'DATE',
        length: null,
        nullable: false,
        defaultValue: null,
        comment: '订单日期'
      },
      {
        name: 'amount',
        type: 'DECIMAL',
        length: '10,2',
        nullable: false,
        defaultValue: '0.00',
        comment: '订单金额'
      },
      {
        name: 'status',
        type: 'VARCHAR',
        length: 20,
        nullable: true,
        defaultValue: 'pending',
        comment: '订单状态'
      }
    ]
    
    upstreamTables.value = [
      {
        id: 'ods_user_behavior',
        name: 'ods_user_behavior',
        comment: '用户行为贴源表',
        type: 'ods',
        relation: 'etl'
      },
      {
        id: 'dim_customer',
        name: 'dim_customer',
        comment: '客户维度表',
        type: 'dim',
        relation: 'join'
      }
    ]
    
    downstreamTables.value = [
      {
        id: 'dws_daily_summary',
        name: 'dws_daily_summary',
        comment: '日汇总表',
        type: 'dws',
        relation: 'aggregate'
      }
    ]
  } else {
    // 其他表的模拟数据
    tableInfo.value = {
      id: tableId,
      name: tableId,
      comment: '示例表',
      type: 'fact',
      rowCount: 100000,
      dataSize: '500MB',
      createTime: new Date('2023-01-01'),
      lastUpdated: new Date()
    }
    
    columns.value = [
      {
        name: 'id',
        type: 'BIGINT',
        length: 20,
        nullable: false,
        defaultValue: null,
        comment: '主键ID'
      }
    ]
    
    upstreamTables.value = []
    downstreamTables.value = []
  }
}

const viewTable = (tableId) => {
  fetchTableDetail(tableId)
}

const viewLineage = () => {
  router.push(`/data-map/lineage/${tableInfo.value.id}`)
  handleClose()
}

const handleClose = () => {
  dialogVisible.value = false
}

// 工具方法
const getTableTypeLabel = (type) => {
  const labels = {
    'fact': '事实表',
    'dim': '维度表',
    'ods': '贴源表',
    'dws': '汇总表'
  }
  return labels[type] || type
}

const getTableTypeTagType = (type) => {
  const types = {
    'fact': 'primary',
    'dim': 'success',
    'ods': 'warning',
    'dws': 'info'
  }
  return types[type] || 'info'
}

const getRelationLabel = (relation) => {
  const labels = {
    'etl': 'ETL处理',
    'join': '关联查询',
    'aggregate': '聚合计算'
  }
  return labels[relation] || relation
}

const getRelationTagType = (relation) => {
  const types = {
    'etl': 'primary',
    'join': 'success',
    'aggregate': 'warning'
  }
  return types[relation] || 'info'
}

const formatNumber = (num) => {
  if (!num) return '0'
  return num.toLocaleString()
}
</script>

<style scoped>
.table-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.lineage-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.lineage-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.lineage-item:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.table-type-indicator {
  width: 6px;
  height: 40px;
  border-radius: 3px;
}

.table-type-indicator.fact { background: #409eff; }
.table-type-indicator.dim { background: #67c23a; }
.table-type-indicator.ods { background: #e6a23c; }
.table-type-indicator.dws { background: #909399; }

.table-info {
  flex: 1;
}

.table-name {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.table-desc {
  font-size: 12px;
  color: #909399;
}

.empty-lineage {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 14px;
}

.dialog-footer {
  text-align: right;
}
</style> 